﻿using DragonSolution.Web.Common.Common;
using DragonSolution.Web.Data.Entity;
using DragonSolution.Web.Data.Enum;
using DragonSolution.Web.UI.DAL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using static DragonSolution.Web.Common.Common.CommonUtil;

namespace DragonSolution.Web.UI.Areas.AdminMrg.Ashx
{
    /// <summary>
    /// 产品数据相关操作
    /// </summary>
    public class MProduct : IHttpHandler
    {

        private JavaScriptSerializer json = new JavaScriptSerializer();
        private int type = (int)Subject.产品;
        private MyDbContext db;

        public void ProcessRequest(HttpContext context)
        {
            string action = context.Request["action"];
            context.Response.ContentType = "application/json;charset=utf-8";
            var jsonObj = string.Empty;
            BaseController bc = new BaseController();
            db = bc.GetContext();

            switch (action)
            {
                case "GetCategoryList":
                    jsonObj = GetCategoryList(context);
                    break;
                case "GetSpiltPageCategoryList":
                    jsonObj = GetSpiltPageCategoryList(context);
                    break;
                case "AddProductType":
                    jsonObj = AddProductType(context);
                    break;
                case "EditProductType":
                    jsonObj = EditProductType(context);
                    break;
                case "DeleteProductType":
                    jsonObj = DeleteProductType(context);
                    break;
                case "GetSpiltPageProductList":
                    jsonObj = GetSpiltPageProductList(context);
                    break;
                case "GetImgList":
                    jsonObj = GetImgList(context);
                    break;
            }

            context.Response.Write(jsonObj);
        }

        /// <summary>
        /// 获取产品类型列表，构建树形菜单
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetCategoryList(HttpContext context)
        {
            try
            {
                var categoryList = db.Category.Where(x => x.SubjectID == type && x.IsDelete == 0).ToList();
                //添加类型的最终父级
                categoryList.Add(new Category() { CategoryID = 0, CategoryName = "产品类型", ParentID = -1, IsDelete = 0, SubjectID = type });
                var list = (from c in categoryList
                            select new
                            {
                                id = c.CategoryID,
                                pId = c.ParentID,
                                name = c.CategoryName
                            });

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess, ResponseData = list });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 获取产品类型分页
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetSpiltPageCategoryList(HttpContext context)
        {
            try
            {
                int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);//页所引
                int pageSize = Convert.ToInt32(context.Request["pageSize"]);//页大小
                int parentTypeId = Convert.ToInt32(context.Request["typeId"]);//父类别id
                var list = db.Category.Where(x => x.IsDelete == 0 && x.SubjectID == type && x.ParentID == parentTypeId).OrderBy(x => x.CreateTime);
                var spl = new SpiltPageList<Category>(list, pageIndex, pageSize);
                return json.Serialize(new { OperateResult = ConstDim.operateSuccess, ResponseData = spl });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 添加产品类型
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string AddProductType(HttpContext context)
        {
            try
            {
                string name = context.Request["name"];
                int parentId = Convert.ToInt32(context.Request["parentId"]);
                Category c = new Category() { CategoryName = name, ParentID = parentId, SubjectID = type, CreateTime = DateTime.Now };
                db.Category.Add(c);
                db.SaveChanges();

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 编辑产品类型
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string EditProductType(HttpContext context)
        {
            try
            {
                string name = context.Request["name"];
                int currentId = Convert.ToInt32(context.Request["currentId"]);
                int parentId = Convert.ToInt32(context.Request["parentId"]);
                Category c = db.Category.Find(currentId);
                if (c != null)
                {
                    c.CategoryName = name;
                    c.ParentID = parentId;
                    db.SaveChanges();
                }

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 删除产品类型(如果有子级，提醒用户先删除子级，这里在前台做了)
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string DeleteProductType(HttpContext context)
        {
            try
            {
                int id = Convert.ToInt32(context.Request["id"]);
                Category c = db.Category.Find(id);
                if (c != null)
                {
                    //db.Category.Remove(c);
                    //逻辑删除
                    c.IsDelete = 1;
                    db.SaveChanges();
                }

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 获取产品分页列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetSpiltPageProductList(HttpContext context)
        {
            try
            {
                int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);//页所引
                int pageSize = Convert.ToInt32(context.Request["pageSize"]);//页大小
                int typeId = Convert.ToInt32(context.Request["typeId"]);//类别id
                string queryName = context.Request["queryName"];
                string queryStartTime = context.Request["queryStartTime"];
                string queryEndTime = context.Request["queryEndTime"];

                var list = db.ProductInfo.Where(x => x.IsDelete == 0);
                if (typeId > 0)
                {
                    list = list.Where(x => x.ProductCategory == typeId);
                }
                if (!string.IsNullOrEmpty(queryName))
                {
                    list = list.Where(x => x.ProductName.Contains(queryName));
                }
                if (!string.IsNullOrEmpty(queryStartTime))
                {
                    DateTime startTime = Convert.ToDateTime(queryStartTime);
                    list = list.Where(x => x.ProductPostTime >= startTime);
                }
                if (!string.IsNullOrEmpty(queryEndTime))
                {
                    DateTime endTime = Convert.ToDateTime(queryEndTime).AddDays(1);
                    list = list.Where(x => x.ProductPostTime < endTime);
                }
                //排序
                list = list.OrderByDescending(x => x.IsTop).ThenByDescending(x => x.ProductPostTime);

                var spl = new SpiltPageList<ProductInfo>(list, pageIndex, pageSize);
                return json.Serialize(new { OperateResult = ConstDim.operateSuccess, ResponseData = spl });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        /// <summary>
        /// 获取产品图片列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public string GetImgList(HttpContext context)
        {
            try
            {
                int proId = Convert.ToInt32(context.Request["proId"]);
                string tableName = "Attachment";
                var attrList = db.Attachment.Where(x => x.IsDelete == 0 && x.TableName == tableName && x.TableID == proId).ToList();
                var list = (from a in attrList
                            select new
                            {
                                FileId = a.AttachmentID,
                                FileName = a.AttachmentName,
                                FileUrl = a.AttachmentPath,
                                FileSize=a.AttachmentSize
                            });

                return json.Serialize(new { OperateResult = ConstDim.operateSuccess, ResponseData = list });
            }
            catch (Exception e)
            {
                return json.Serialize(new { OperateResult = ConstDim.operateFailed, ResponseData = e.Message });
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}